<?php
/**
 * Created by PhpStorm.
 * User: xi
 * Date: 16/2/23
 * Time: AM11:00
 */

namespace Api\Util;


class Helper {


    public static function mkDirs($dir){
        if(!is_dir($dir)){
            if(!Helper::mkDirs(dirname($dir))){
                return false;
            }
            if(!mkdir($dir,0777)){
                return false;
            }

        }
        return true;
    }

    public static  function  curl_request($url){


        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;

    }

    public static  function curlRequest($url, $postData = array(), $launch = 'post', $contentType = 'text/html')
    {
        $result = "";
        try {
            $header = array("Content-Type:" . $contentType . ";charset=utf-8");
            if (!empty($_SERVER['HTTP_USER_AGENT'])) {        //是否有user_agent信息
                $user_agent = $_SERVER['HTTP_USER_AGENT'];
            }
            $cur = curl_init();
            curl_setopt($cur, CURLOPT_URL, $url);
            curl_setopt($cur, CURLOPT_HEADER, 0);
            curl_setopt($cur, CURLOPT_HTTPHEADER, $header);
            curl_setopt($cur, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($cur, CURLOPT_TIMEOUT, 30);
            //https
            curl_setopt($cur, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($cur, CURLOPT_SSL_VERIFYHOST, FALSE);
            if (isset($user_agent)) {
                curl_setopt($cur, CURLOPT_USERAGENT, $user_agent);
            }
            curl_setopt($cur, CURLOPT_ENCODING, 'gzip');
            if (is_array($postData)) {
                if ($postData && count($postData) > 0) {
                    $params = http_build_query($postData);
                    if ($launch == 'get') {        //发送方式选择
                        curl_setopt($cur, CURLOPT_HTTPGET, $params);
                    } else {
                        curl_setopt($cur, CURLOPT_POST, true);
                        curl_setopt($cur, CURLOPT_POSTFIELDS, $params);
                    }
                }
            } else {
                if (!empty($postData)) {
                    $params = $postData;
                    if ($launch == 'post') {
                        curl_setopt($cur, CURLOPT_POST, true);
                        curl_setopt($cur, CURLOPT_POSTFIELDS, $params);
                    }
                }
            }
            $result = curl_exec($cur);
            curl_close($cur);
        } catch (Exception $e) {

        }
        return $result;
    }

    /**
     * 记录操作日志
     * 
     * @param mixed $data 需要记录的数据
     * @param string error_type 日志类型
     */
    public static function log($data, $log_type = 'warning', $log_format = "Y_m_d") {
        $config = C('log');
        // 读取配置，如果有设置，优先读取设置里的值，否则自己去组装地址
        if(isset($config[$log_type])){
            $log = $config[$log_type];
            $log['format'] = $log_format;
        }else{
            // 先配置一个默认的log handle
            $log_default = $config['default'];
            $log = array(
                'path' => $log_default['path'].$log_type.'/',
                'format' => $log_format
            );
        }
        if(!is_dir($log['path'])){
            Helper::mkDirs($log['path']);
        }

        $file = $log['path'].date($log['format']).'.log';
        $msg = '';
        if(is_array($data)){
            $msg = json_encode($data);
        }else{
            $msg = $data;
        }
        $datetime = date('Y-m-d H:i:s');
        $msg = $datetime.' '.$msg."\r\n";
        @file_put_contents($file, $msg, FILE_APPEND);
        return;
    }

    /**
     * 使用文件记录操作日志
     * 
     * @param mixed $data 需要记录的数据
     * @param string $log_type 日志类型
     */
    public static function logfile($data, $log_type = 'wechat_check', $log_format = "Y_m_d") {
        $config = C('log');
        // 读取配置，如果有设置，优先读取设置里的值，否则自己去组装地址
        if(isset($config[$log_type])){
            $log = $config[$log_type];
            $log['format'] = $log_format;
        }else{
            // 先配置一个默认的log handle
            $log_default = $config['default'];
            $log = array(
                'path' => $log_default['path'].$log_type.'/',
                'format' => $log_format
            );
        }
        if(!is_dir($log['path'])){
            Helper::mkDirs($log['path']);
        }
        $file = $log['path'].date($log['format']).'.log';
        $msg = '';
        if(is_array($data)){
            $msg = json_encode($data);
        }else{
            $msg = $data;
        }
        @file_put_contents($file, $msg);
        return;
    }

    /**
     * 获取文件操作日志路径
     * 
     * @param mixed $data 需要记录的数据
     * @param string error_type 日志类型
     */
    public static function get_logfile($log_type = 'wechat_check', $log_format = "Y_m_d") {
        $config = C('log');
        // 读取配置，如果有设置，优先读取设置里的值，否则自己去组装地址
        if(isset($config[$log_type])){
            $log = $config[$log_type];
            $log['format'] = $log_format;
        }else{
            // 先配置一个默认的log handle
            $log_default = $config['default'];
            $log = array(
                'path' => $log_default['path'].$log_type.'/',
                'format' => $log_format
            );
        }
        if(!is_dir($log['path'])){
            Helper::mkDirs($log['path']);
        }
        $file = $log['path'].date($log['format']).'.log';
        return $file;
    }

    /**
     * 生成加密的auth_cookie
     *
     * @param string $openid
     * @param int $uid
     * @param string $salt
     * @param int $expire
     */
    public static function get_auth_cookie($openid, $uid, $salt = "", $expire = 0) {
        $auth = C('SECRET_KEY');
        $str = $openid.'|'.$uid.'|'.$salt.'|'.$expire;
        return Aes::encode($auth, $str);
    }

    /**
     * 解密auth_cookie
     *
     * @param string $openid
     * @param int $uid
     * @param string $salt
     * @param int $expire
     */
    public static function open_auth_cookie($auth_key) {
        $key = C('SECRET_KEY');;
        $values = array('', 0, '' ,0);
        if($auth_key){
            try{
                $decode = Aes::decode($key, $auth_key);
                if($decode){
                    $values = explode('|', $decode);
                    $values[1] = intval($values[1]);
                    $values[3] = intval($values[3]);
                }
            }catch(Exception $e){
                // 这里仅记录错误日志
                Helper::log($auth_key, 'auth_cookie');
            }
        }
        $keys = array(
            'openid',
            'uid',
            'salt',
            'expire'
        );
        return array_combine($keys, $values);
    }
} 